<template>
  <div class="category-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="分类名称">
          <el-input v-model="searchForm.name" placeholder="请输入分类名称" clearable/>
        </el-form-item>
        <el-form-item label="所属餐厅">
          <el-select v-model="searchForm.restaurantId" style="width: 150px" placeholder="请选择餐厅" clearable>
            <el-option
              v-for="item in restaurants"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增分类</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" border>
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <el-table-column prop="name" label="分类名称"/>
        <el-table-column prop="sort" label="排序" width="80" align="center"/>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称"/>
        </el-form-item>
        <el-form-item label="所属餐厅" prop="restaurantId">
          <el-select v-model="formData.restaurantId" placeholder="请选择餐厅">
            <el-option
              v-for="item in restaurants"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="99"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCategoryPage, saveCategory, updateCategory, deleteCategory } from '@/api/category'
import { getRestaurantList } from '@/api/restaurant'
import { formatDateTime } from '@/utils/format'

// 搜索表单
const searchForm = ref({
  name: '',
  restaurantId: ''
})

// 餐厅列表
const restaurants = ref([])

// 获取餐厅列表
const getRestaurants = async () => {
  try {
    const res = await getRestaurantList();
    restaurants.value = res.data
  } catch (error) {
    console.error('获取餐厅列表失败:', error)
  }
}

// 分页参数
const page = ref({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await getCategoryPage({
      pageNum: page.value.current,
      pageSize: page.value.size,
      name: searchForm.value.name,
      restaurantId: searchForm.value.restaurantId
    })
    tableData.value = res.data.records
    page.value.total = res.data.total
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value.current = 1
  getList()
}

// 重置
const handleReset = () => {
  searchForm.value.name = ''
  searchForm.value.restaurantId = ''
  handleSearch()
}

// 编辑弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const formData = ref({
  id: '',
  name: '',
  restaurantId: '',
  sort: 0
})

// 表单校验规则
const formRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  restaurantId: [{ required: true, message: '请选择所属餐厅', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增分类'
  dialogVisible.value = true
  formData.value = {
    id: '',
    name: '',
    restaurantId: '',
    sort: 0
  }
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑分类'
  dialogVisible.value = true
  formData.value = { ...row }
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCategory(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()

  try {
    if (formData.value.id) {
      await updateCategory(formData.value)
      ElMessage.success('编辑成功')
    } else {
      await saveCategory(formData.value)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('保存失败:', error)
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  page.value.size = val
  getList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  page.value.current = val
  getList()
}

onMounted(() => {
  getRestaurants()
  getList()
})
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
